package com.manage.action;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import com.action.AbstractAction;
import com.manage.cache.BlackNumberManager;
import com.manage.cache.SpInfoManager;
import com.manage.model.BlackNumber;
import com.manage.model.SpInfo;

public class BlackNumberAction extends AbstractAction {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private Logger logger;
	
	public BlackNumberAction()
	{
		logger = Logger.getLogger(this.getClass());
	}
	
	public String execute()
	{
		return SUCCESS;
	}

	private List<BlackNumber> list;
	private BlackNumber       model;
	private String        type;
	private List<SpInfo> splist;
	
	private File blackFile;
	
	public String list()
	{
		logger.debug("list account");
		list = BlackNumberManager.getInstance().getBlackNumbers();
		splist = SpInfoManager.getInstance().getSpInfos();
		return SUCCESS;
	}
	
	public String show()
	{
		splist = SpInfoManager.getInstance().getSpInfos();
		if (model != null && model.getId() >= 0)
		{
			model = BlackNumberManager.getInstance().getBlackNumber(model.getId());
			type = "update";
		}
		else
		{
			model = new BlackNumber();
			model.setId(-1);
			type = "insert";
		}

		return SUCCESS;
	}
		
	public String save()
	{
		List<String> list = new ArrayList<String>();
		if (model.getNumber() != null && model.getNumber().length() > 0)
			list.add(model.getNumber());
		
		 try 
		 {   
			 if (blackFile != null)
			 {
	            FileReader f_reader = new FileReader(blackFile);   
	            BufferedReader reader = new BufferedReader(f_reader); 
	            String str = "";; 
	            while ((str = reader.readLine()) != null)
	            {  
	            	str = str.trim();
	            	if (str.length() > 0)
	            	{
	        			list.add(str);
	            	}
	            }
	            reader.close();
	            f_reader.close();
			 }
			 else {
				 logger.error("blackFile is null!");
			 }
        } 
		catch (Exception e) 
        {   
           logger.error(e.getMessage());
        }
		BlackNumberManager.getInstance().saveBlackNumber(type, model, list);
		return SUCCESS;
	}

	public List<BlackNumber> getList() {
		return list;
	}

	public void setList(List<BlackNumber> list) {
		this.list = list;
	}

	public BlackNumber getModel() {
		return model;
	}

	public void setModel(BlackNumber model) {
		this.model = model;
	}

	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}

	public List<SpInfo> getSplist() {
		return splist;
	}

	public void setSplist(List<SpInfo> splist) {
		this.splist = splist;
	}

	/**
	 * @return the blackFile
	 */
	public File getBlackFile() {
		return blackFile;
	}

	/**
	 * @param blackFile the blackFile to set
	 */
	public void setBlackFile(File blackFile) {
		this.blackFile = blackFile;
	}
	
	
}
